package com.twentyOne.ClothingLand.action;

import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;
import com.twentyOne.ClothingLand.service.IStockService;
import com.twentyOne.ClothingLand.service.impl.StockService;
import com.twentyOne.ClothingLand.util.JsonUtil;
import com.twentyOne.ClothingLand.vo.Stock;

public class StockAction extends ActionSupport {

	private Stock stock;
	private IStockService stockService = new StockService();

	public Stock getStock() {
		return stock;
	}

	public void setStock(Stock stock) {
		this.stock = stock;
	}	

	public String addStock() throws Exception {

		this.stockService.addStock(stock);
		return null;

	}

	public String deleteStock() throws Exception {

		this.stockService.deleteStock(stock);
		return null;

	}

	public String modifyStock() throws Exception {

		Stock stock_ = this.stockService.searchStockByInfo(stock.getStockId(), stock.getType(), stock.getBarcode());
		stock.setId(stock_.getId());
		this.stockService.modifyStock(stock);
		return null;

	}

	public String addStockQuantity() throws Exception {

		Stock stock_ = this.stockService.searchStockByInfo(stock.getStockId(), stock.getType(), stock.getBarcode());
		stock.setId(stock_.getId());
		stock.setQuantity(stock_.getQuantity() + stock.getQuantity());
		this.stockService.modifyStock(stock);
		return null;

	}
	
	public String decreaseStockQuantity() throws Exception {

		Stock stock_ = this.stockService.searchStockByInfo(stock.getStockId(), stock.getType(), stock.getBarcode());
		stock.setId(stock_.getId());
		stock.setQuantity(stock_.getQuantity() - stock.getQuantity());
		this.stockService.modifyStock(stock);
		return null;

	}

	public String searchAllStock() throws Exception {

		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		List<Stock> list = this.stockService.searchAllStock(stock.getStockId(), stock.getType());

		if (list != null) {
			String stocksJson = JsonUtil.objectsToJson(list);
			out.print(stocksJson);
		} else {
			out.print("[{\"Nothing\":\"Nothing\"}]");
		}
		return null;

	}

	public String searchStockByInfo() throws Exception {

		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		Stock stock_ = this.stockService.searchStockByInfo(stock.getStockId(), stock.getType(), stock.getBarcode());

		if (stock_ != null) {
			String stockJson = JsonUtil.objectToJson(stock_);
			out.print(stockJson);
		} else {
			out.print("[{\"Nothing\":\"Nothing\"}]");
		}
		return null;

	}

}
